package admin

import (
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
	"zhuandan/redis_lib"
	"zhuandan/utils"
)

// 供应商采购单已确认通知
func Caigou(openid, title string, infosjbid, uid int64) (data T) {
	if infosjbid > 0 {
		layout := "2006-01-02 15:04:05"

		// 获取当前时间
		now := time.Now()

		// 格式化时间
		formatted := now.Format(layout)
		token := Accesstokengzh()
		//token := "85_dwUYrC-sdCOHebM9X7bVlZbEdA4YzyVD71h1j3ONo2BXmX7QuBzMnXICV25t4UWXrwx8_6p444WtG1liZMqA7ryvej2m99gpw5D8gFlAA8CkWaadNbYOIwTEqFMRYJdACALSD"
		//fmt.Println(token)
		d := map[string]interface{}{
			"touser":      openid,
			"template_id": "uxjeShJlBgc80ltBWMDO_esUL1S-N_cB6yDDqDO5rnM",
			"url":         "http://yyb.suishilian.com/#/pages/OrderDetails/OrderDetails?Id=" + utils.Int64string(infosjbid),
			"data": map[string]interface{}{
				"first": map[string]interface{}{ //产品名称
					"value": "新询价单通知",
				},
				"keyword1": map[string]interface{}{ //合计数量
					"value": "************",
				},
				"keyword2": map[string]interface{}{ //制单人
					"value": formatted,
				},
				"keyword3": map[string]interface{}{ //制单人
					"value": title,
				},
				"keyword4": map[string]interface{}{ //制单人
					"value": 1,
				},
			},
		}
		dJson, _ := json.Marshal(d)
		sJson := string(dJson)
		//fmt.Println(sJson)
		r := HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token, sJson, "", d, uid, infosjbid)
		return r
	}
	return T{}
	//fmt.Println(resp)
}

// 供应商采购单已确认通知
func Caigoucs(openid, title string, infosjbid, uid int64) {
	if infosjbid > 0 {
		layout := "2006-01-02 15:04:05"

		// 获取当前时间
		now := time.Now()

		// 格式化时间
		formatted := now.Format(layout)
		token := Accesstokengzhcs()
		//token := "85_D84Ozd9mirqvz0DjpKON6rtviQ_f-oRXHRxvwvvqPSlHAdBSn2XiyAUvmk7GhH9JwNpkPivOeRUvVRQdVnA3PEcC33QoUAKHyBVA92Gby6m5KA6ozFbIHqKpv2MTYLfAGAEJW"
		//fmt.Println(token)
		d := map[string]interface{}{
			"touser":      openid,
			"template_id": "ERFcWTSWN-Mm5w1JWYj3bBdWLzF77KmaTUfFDENzyjU",
			"url":         "http://yyb.suishilian.com/#/pages/OrderDetails/OrderDetails?Id=" + utils.Int64string(infosjbid),
			"data": map[string]interface{}{
				"first": map[string]interface{}{ //产品名称
					"value": "新询价单通知",
				},
				"keyword1": map[string]interface{}{ //合计数量
					"value": "************",
				},
				"keyword2": map[string]interface{}{ //制单人
					"value": formatted,
				},
				"keyword3": map[string]interface{}{ //制单人
					"value": title,
				},
				"keyword4": map[string]interface{}{ //制单人
					"value": "1",
				},
				"remark": map[string]interface{}{ //制单人
					"value": "点击本条信息进行操作，您可以答复询价、查看询价单位信息、忽略此询价单等",
				},
			},
		}
		dJson, _ := json.Marshal(d)
		sJson := string(dJson)
		//fmt.Println(sJson)
		HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token, sJson, "", d, uid, infosjbid)
	}

	//fmt.Println(resp)
}
func HttpPost(url, params string, contentType string, retMap interface{}, uid, infosjbid int64) (data T) {
	if contentType == "" {
		contentType = "application/json"
		// "application/x-www-form-urlencoded"
	}
	//fmt.Println(params)
	resp, err := http.Post(url,
		contentType,
		strings.NewReader(params))
	if err != nil {
		fmt.Println(err)
	}

	defer func() {
		_ = resp.Body.Close()
	}()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
	}
	//fmt.Println(string(body))

	err = json.Unmarshal(body, retMap)
	if err != nil {
		fmt.Println(err)
	}

	r := T{}
	err = json.Unmarshal(body, &r)
	return r
}

type T struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Msgid   int64  `json:"msgid"`
}
type ResponseAccess struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int64  `json:"expires_in"`
}

const (
	appidywd     = "wxa302f6cf7330d474"
	appsecretywd = "7e77c81653d7f8ea6206a0fb3e834fa8"
)

func Accesstokengzh() (data string) {
	ctx := context.Background()
	weixintoken, _ := redis_lib.Client.Get(ctx, "weixinAccesstokendyewuduo").Result()
	if weixintoken == "" || len(weixintoken) == 0 {
		resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appidywd + "&secret=" + appsecretywd)

		if err != nil {
			fmt.Println(err)
			return
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		r := ResponseAccess{}
		//fmt.Println("token----------", string(body))

		//把请求到的结构反序列化到专门接受返回值的对象上面
		err = json.Unmarshal(body, &r)
		if err != nil {
			fmt.Println(err)
		}
		weixintoken = r.AccessToken
		redis_lib.Client.Set(ctx, "weixinAccesstokendyewuduo", weixintoken, 7000*time.Second)
	}
	return weixintoken

}

const (
	appid     = "wxf64aa6106b875289"
	appsecret = "dad526019f10a9d8acf67b225948563a"
)

func Accesstokengzhcs() (data string) {
	ctx := context.Background()
	weixintoken, _ := redis_lib.Client.Get(ctx, "weixinAccesstokendzhuandanbao").Result()
	if weixintoken == "" || len(weixintoken) == 0 {
		resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret)

		if err != nil {
			fmt.Println(err)
			return
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		r := ResponseAccess{}
		//fmt.Println("token----------", string(body))
		tokenlog := models.Tokenlog{
			Addtime: time.Now().Unix(),
			Value:   string(body),
			Appid:   appid,
		}
		data_source.Db.Create(&tokenlog)
		//把请求到的结构反序列化到专门接受返回值的对象上面
		err = json.Unmarshal(body, &r)
		if err != nil {
			fmt.Println(err)
		}
		weixintoken = r.AccessToken
		redis_lib.Client.Set(ctx, "weixinAccesstokendzhuandanbao", weixintoken, 7000*time.Second)
	}
	return weixintoken

}
